//
//  WBNetworkManager.swift
//  郑好微博
//
//  Created by WF on 2017/6/28.
//  Copyright © 2017年 WF. All rights reserved.
//

import UIKit
import AFNetworking

/// Swift 的枚举支持任意数据类型
/// switch / enum 在OC中都只是支持整数
enum WBHTTPMethod {
    case GET
    case POST
}

/// 网络管理
class WBNetworkManager: AFHTTPSessionManager {
    
    /// 静态区/常量/闭包
    /// 在第一次访问时，执行闭包，并且将结果保存在 shared 常量中
    static let shared = WBNetworkManager()
    
    var accessToken: String? = "2.007YkUnBVZhrCC0bd398b4840mrpmg"
    
    /// 专门负责拼接 token 的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) {
        
        guard let token = accessToken else {
            print("没有 tiken! 需要登录")
            
            completion(nil, false)
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            parameters = [String: Any]()
        }
        
        parameters!["access_token"] = token
        
        request(URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    /// 封装 AFN 的 GET / POST 请求
    ///
    /// - Parameters:
    ///   - method: GET / POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调[json(字典/数组)，是否成功]
    func request(method:WBHTTPMethod = .GET, URLString: String, parameters: [String: Any], completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) {
        
        // 成功回调
        let success = { (task: URLSessionDataTask, json: Any?)->() in
            completion(json, true)
        }
        
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            // error 通常比较吓人，例如编号：XXXX,错误原因一堆英文
            print("网络请求错误 \(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}
